<template>
  <div class="change-password-container">
    <div class="change-password-card">
      <div class="change-password-title">修改密码</div>
      <div class="change-password-subtitle">请输入您的旧密码和新密码</div>
      
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="0">
        <el-form-item prop="oldPassword">
          <el-input
            v-model="formData.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            :disabled="loading"
          />
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            v-model="formData.newPassword"
            type="password"
            placeholder="请输入新密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            :disabled="loading"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            :disabled="loading"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="change-password-button" type="primary" @click="onSubmit" :loading="loading">
            {{ loading ? '修改中...' : '修改密码' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="change-password-footer">
        <el-button type="text" @click="goBack" :disabled="loading">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import { changePassword } from '@/api/user'
import { userStorage } from '@/utils/storage'

const router = useRouter()
const formRef = ref()
const loading = ref(false)
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能少于6位'))
  } else if (!/^(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
    callback(new Error('密码必须包含字母和数字'))
  } else {
    callback()
  }
}

// 确认密码验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== formData.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const onSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true
    
    // 获取当前用户ID
    const currentUser = userStorage.getCurrentUser()
    if (!currentUser || !currentUser.id) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }

    const result = await changePassword(currentUser.id, {
      oldPassword: formData.value.oldPassword,
      newPassword: formData.value.newPassword,
      confirmPassword: formData.value.confirmPassword
    })

    if (result && result.code === 200) {
      ElMessage.success('密码修改成功')
      // 清空表单
      formData.value = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      // 返回上一页
      goBack()
    } else {
      ElMessage.error(result?.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error(error?.response?.data?.message || '密码修改失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  if (router.currentRoute.value.query.from) {
    router.push(router.currentRoute.value.query.from)
  } else {
    router.go(-1)
  }
}

onMounted(() => {
  // 检查用户是否已登录
  const token = userStorage.getToken()
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
  }
})
</script>

<style scoped>
.change-password-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.change-password-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.change-password-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 8px;
}

.change-password-subtitle {
  font-size: 14px;
  color: #666;
  text-align: center;
  margin-bottom: 32px;
}

.change-password-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
}

.change-password-footer {
  text-align: center;
  margin-top: 24px;
}

.change-password-footer .el-button {
  color: #666;
  font-size: 14px;
}

.change-password-footer .el-button:hover {
  color: #409eff;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  height: 48px;
}

:deep(.el-input__inner) {
  font-size: 14px;
}
</style>
